import GameData from "../libs/GameData";
import Helper from "../libs/HelperMgr";
import GameManager from "./GameManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Stosh extends cc.Component {


    public _parabolaTrace: Array<cc.Vec2> = new Array();
    private _traceIndex: number = 0;
    private _tweening: boolean = false;


    async onLoad() {
        let img =  this.node.getChildByName("img").getComponent(cc.Sprite);
        img.spriteFrame  =  await Helper.loadRes(`image/stosh${GameData.instance.playStosh}`, cc.SpriteFrame)
        
    }

    start() {
        this._tweening = false;
        this._traceIndex = 0;
        if (this._parabolaTrace.length > 0) {
            this.node.setPosition(this._parabolaTrace[this._traceIndex].x, this._parabolaTrace[this._traceIndex].y)
        }
        GameData.instance.playStoshs[GameData.instance.playStosh-1] --;
    }

    tweenFollowTrace() {
        if (this._traceIndex < this._parabolaTrace.length - 1) {
            this._tweening = true;
            this._traceIndex += 1;
            cc.tween(this.node).to(0.01, { x: this._parabolaTrace[this._traceIndex].x, y: this._parabolaTrace[this._traceIndex].y }).call(() => {
                this._tweening = false;
                if(this._traceIndex == this._parabolaTrace.length - 1 && GameData.instance.playStoshs[GameData.instance.playStosh-1] <=0){
                    GameManager.instace.playerIsStosh = false;
                }
            }).start()
        }
    }


    update(dt) {
        if(GameManager.instace.gameIsStart && !GameManager.instace.gameIsOver){
            if (this.node.y <= GameManager.instace.ground.y) {
                this.node.y = GameManager.instace.ground.y
            } else {
                if (this._parabolaTrace.length > 0 && !this._tweening) {
                    if (Helper.getDistance(this.node.x, this.node.y, this._parabolaTrace[this._traceIndex].x, this._parabolaTrace[this._traceIndex].y) <= 1) {
                        this.tweenFollowTrace();
                    }
    
                }
            }
        }
        

    }
}
